const config = require('../../config.js');
const utils = require('../../utils/util.js');
const request = require('../../utils/request.js')
const QQMapWX = require('../../sdk/qqmap-wx-jssdk.min.js');
import { getIndexData, getIndexList, getCategoryList, getTradeArea, getIndexBanner } from '../../static/api/api.js'
//获取应用实例
var app = getApp()
Page({
    data: {
        indexData:null,
        listData: null,
        isNoMore: false,
        pageLoad: false,
        pages: {
            curPage: 1,
            totalPage: 1
        },
        isShowNewCoupon: false,
        indicatorDots: true,
        autoplay: true,
        interval: 3000,
        duration: 500,
        isFilter: false,
        curLocation:{
            address:'',
            poi:{
                latitude: '',
                longitude: ''
            }
            
        },
        isShowfilter:false,
        isShowFade: false,
        curSearchKey: '',
        serviceType: 'door',
        searchParamsData:{
            doorDate:'',
            allType:'',
            aiType:'',
            sAllType:'',
            sAiType:'',
            sArea:'',
            sDis:''
        },
        
        searchParams: {
            //上门时间
            'doorDate': [],
            //全部类型
            'allType': [],
            //智能排序
            'aiType': [{
                    name: '人气高到低',
                    id: 1
                },
                {
                    name: '距离从近到远',
                    id: 2
                }
            ],
            'sAllType': [],
            'sAiType':[
                {
                    name: '人气高到低',
                    id: 1
                },
                {
                    name: '销量从高到底',
                    id: 2
                }
            ]
        },
        tradeArea:null,
        curTradeArea:null,
        tradeAreaPart:[],
        curTradeAreaPart:null,
        isScroll:false,
        disArr:{
            id:0,
            name:'附近',
            child_area:[
                {
                    id: '',
                    name: '全部'
                },
                {
                    id:1,
                    name:'1KM以内'
                },
                {
                    id: 2,
                    name: '2KM以内'
                },
                {
                    id: 3,
                    name: '3KM以内'
                }
            ]

        },
        scrollTop:0,

    },
    onPullDownRefresh: function () {
        let that = this;
        this.getLocation()
        this.getTradeArea()
        this.getIndexData()
        //this.getIndexList()

    },
    onShow: function() {
        this.setData({
            'pageLoad': false
        })
        let that = this;
        this.getLocation()
        this.getTradeArea()
        
        this.getIndexData()
        this.showTip()
        this.mainIndexScroll()
        this.getIndexBanner()
        
    },
    onUnload: function () {
        
    },
    onLoad: function(options) {
        
    },
    showTip(){
        let that = this;
        if (!wx.getStorageSync('isShowTip')) {
            this.setData({
                'isShowTip': true
            })
            setTimeout(function () {
                that.setData({
                    'isShowTip': false
                })
                wx.setStorageSync('isShowTip', true)
            }, 5000)
        }
    },
    onReachBottom(){
        this.getIndexList()
    },
    getLocation(){
        let that = this;
        let locationData = wx.getStorageSync('locationData')
        console.log(locationData)
        if (locationData){
            that.setData({
                'curLocation': locationData
            })
            that.getIndexList()
            console.log(locationData)
            return;
        }
        wx.getLocation({
            success: function (res) {
                console.log('获取地址的经纬度')
                console.log(res)
                let qqmapsdk = new QQMapWX({
                    key: config.qqMapKey
                });
                qqmapsdk.reverseGeocoder({
                    type:'wgs84',
                    location: {
                        latitude: res.latitude,
                        longitude: res.longitude
                    },
                    // get_poi: 1,
                    // poi_options: 'policy=2;radius=3000;page_size=20;page_index=1',
                    success: function (res) {
                       console.log('授权地址')
                       console.log(res)
                        res.result.ad_info.location = res.result.location
                        let poiData = {
                            poi: res.result.ad_info,
                            address: res.result.address
                        }
                        that.setData({
                            'curLocation': poiData
                        })
                        console.log('请求历史')
                        console.log(that.data.curLocation)
                        that.getIndexList()
                        wx.setStorageSync('locationData', poiData)
                    },
                    fail: function (res) {
                        console.log(res);
                        wx.getSetting({
                            success(res) {
                                if (!res.authSetting['scope.userLocation']) {
                                    let poiData = config.defaultLocData
                                    that.setData({
                                        'curLocation': poiData
                                    })
                                    wx.setStorageSync('locationData', poiData)
                                }
                            }
                        })
                    }
                })
            },
        })
        
    },
    onPageScroll: function(e) {
        this.setData({
            'scrollTop': e.scrollTop
        })
        this.mainIndexScroll(e)

    },
    mainIndexScroll(e){
        let that = this;
        if(this.data.isScroll){
            return;
        }
        if (this.data.scrollTop >= 279) {
            if (this.data.isShowFade) return;
            wx.setNavigationBarColor({
                frontColor: '#ffffff',
                backgroundColor: '#FF5477',
            })
            that.setData({
                'isFilter': true,
                'isShowFade': true,
                'curSearchKey': this.data.isShowFade ? this.data.curSearchKey:'',
                'isShowfilter':false,
            })
        } else {
            if (!this.data.isShowFade) return;
            wx.setNavigationBarColor({
                frontColor: '#000000',
                backgroundColor: '#ffffff',
            })
            that.setData({
                'isFilter': false,
                'isShowFade': false,
                'isShowfilter': false,
            })
        }
    },
    onPullDownRefresh: function() {
        let that = this;
        wx.hideLoading()
        wx.stopPullDownRefresh()
    },
    showFilterBox(e) {
        console.log('开始出现')
        let key = e.currentTarget.dataset.key;
        this.setData({
            'isFilter': true,
            'curSearchKey': key,
            'isShowFade': true
        })
        wx.pageScrollTo({
            scrollTop: 279
        })
    },
    hideFilterBox() {
        this.setData({
            'isFilter': false,
            'isShowFade': false,
            'isShowfilter': false,
            'curSearchKey':''
        })
    },
    classifyClick(e){
        let dataset = e.currentTarget.dataset.item;
        console.log(dataset)
        if (this.data.serviceType=='door'){
            this.setData({
                'searchParamsData.allType.id': dataset.category_id,
                'searchParamsData.allType.name': dataset.category_name,
                'searchParamsData.allType.main_img': dataset.main_img,
                'searchParamsData.allType.isSelected':true
            })
            
        }else{
            this.setData({
                'searchParamsData.sAllType.id': dataset.category_id,
                'searchParamsData.sAllType.name': dataset.category_name,
                'searchParamsData.sAllType.main_img': dataset.main_img,
                'searchParamsData.sAllType.isSelected': true
            })
        }
        this.setData({
            'pages.curPage': 1,
            'pages.totalPage': 1,
            'curSearchKey': '',
            'curSearchKey': '',
            'pageLoad': false,
            'listData': null,
            'isNoMore': false,
            'isScroll': false
        })
        this.getIndexList()
    },
    showParams(e) {
        let that = this;
        let key = e.currentTarget.dataset.key;
        this.setData({
                'isShowFade': (key != this.data.curSearchKey)?'true': !this.data.isShowFade,
            'curSearchKey': key,
            'isFilter': true,
            'isShowfilter':true
        })
        if (e.currentTarget.dataset.type=='2'){
            wx.pageScrollTo({
                'scrollTop': 329,
            })
            this.setData({
                'isScroll':true,
                'isShowFade':false
            })
            setTimeout(function(){
                that.setData({
                    'isScroll': false
                }) 
            },1000)
        }
       
       
    },
    countSearchDate() {
        let data = new Date(this.data.indexData.service_time_list[0].date.replace(/-/g,'/'));
       
        let ctime = data.getTime();
        let tArr = [];
        tArr.push({
            name: '全部',
            id: ''
        })
        for (let i = 1; i <= 7; i++) {
            let cname, nDate;
            
            nDate = new Date(ctime);
            cname = (nDate.getMonth() + 1) + '月' + (nDate.getDate()) + '日'
            if (i == 1) cname = '今天'
            if (i == 2) cname = '明天'

            tArr.push({
                name: cname,
                id: utils.formatDate(nDate,'yyyy-MM-dd')
            })
            ctime += 24 * 60 * 60 * 1000;
            
        }
        this.setData({
            'searchParams.doorDate': tArr
        })
    },
    changeServiceType(e) {
        let type = e.currentTarget.dataset.type;
        this.setData({
            serviceType: type
        })
        this.setData({
            'pages.curPage': 1,
            'pages.totalPage': 1,
            'curSearchKey':'',
            'curSearchKey':'',
            'pageLoad': false,
            'listData': null,
            'isNoMore': false,
            'isScroll':false
        })
        this.mainIndexScroll()
        this.getIndexList()
    },
    getIndexData(){
        let params = {}
        wx.showLoading({
            title: '加载中...',
        })
        getIndexData(params).then(response => {
            wx.hideLoading()
            let data = response.data;
            this.setData({
                'indexData': data
            })
            let cdata = [],tdata=[];
            console.log(response.data.category)
            response.data.category.forEach((el, index) => {
                cdata.push({
                    name: el.category_name,
                    id: el.category_id,
                    main_img:el.main_img
                })
            })
            this.setData({
                'searchParams.allType': cdata,
                'searchParams.sAllType': cdata
            })
            this.countSearchDate()
        }).catch(response => {
            wx.hideLoading()
        })
    },
    getIndexBanner() {
        let params = {}
        getIndexBanner().then(response => {
            let data = response.data;
            this.setData({
                'bannerData': data
            })
            
        }).catch(response => {
        })
    },
    getIndexList() {
        if (this.data.pageLoad) return;
        if (this.data.pages.curPage > this.data.pages.totalPage) return;
        this.setData({
            pageLoad: true
        })
        let that = this;
        let params;
        console.log('请求地址')
        console.log(this.data.curLocation)
        if (this.data.serviceType == 'door'){
            params = {
                page: this.data.pages.curPage,
                longitude: this.data.curLocation.poi.location.lng,
                latitude: this.data.curLocation.poi.location.lat,
                request_type: 1,
                category_id: this.data.searchParamsData.allType ? this.data.searchParamsData.allType.id : '',
                order_type: this.data.searchParamsData.aiType ? this.data.searchParamsData.aiType.id : '',
                set_date: this.data.searchParamsData.doorDate ? this.data.searchParamsData.doorDate.id : '',
            }
        }else{
            params = {
                page: this.data.pages.curPage,
                longitude: this.data.curLocation.poi.location.lng,
                latitude: this.data.curLocation.poi.location.lat,
                request_type: 2,
                distance: this.data.searchParamsData.sDis ? this.data.searchParamsData.sDis.id:'',
                service_area_id: this.data.searchParamsData.sArea ? this.data.searchParamsData.sArea.id:'',
                category_id: this.data.searchParamsData.sAllType ? this.data.searchParamsData.sAllType.id : '',
                order_type: this.data.searchParamsData.sAiType ? this.data.searchParamsData.sAiType.id : ''
            }
        }
        
        getIndexList(params).then(response => {
            let data = response.data;
            if (that.data.pages.curPage == 1) {
                that.setData({
                    listData: data.lists
                })
            } else {
                that.setData({
                    listData: that.data.listData.concat(data.lists)
                })
            }
            that.setData({
                'pages.curPage': that.data.pages.curPage + 1,
                'pages.totalPage': data.page.total_page,
                'pageLoad': false
            })
            
            if (this.data.pages.curPage >= this.data.pages.totalPage) {
                this.setData({
                    isNoMore: true
                })
            };
        }).catch(response => {
            that.setData({
                'pageLoad': false
            })
        })

    },
    goUrl(e) {
        utils.goNavigationUrl(e)
    },
    getTradeArea() {
        let that = this;
        getTradeArea({}).then(response => {
            response.data.unshift(this.data.disArr)
            this.setData({
                'tradeArea':response.data,
                
                'curTradeArea':response.data[0]
            })
        }).catch(response => {
            console.log(response)
        })
    },
    sItemClick(e){
        let dataset = e.currentTarget.dataset;
        this.data.searchParams[this.data.curSearchKey].forEach((el,index)=>{
            let flag = el.isSelected;
            let key = `searchParams.${this.data.curSearchKey}[${index}].isSelected`;
            let dataKey = `searchParamsData.${this.data.curSearchKey}`;
            if (dataset.item.id == el.id){
                this.setData({
                    [key]:!flag,
                    [dataKey]:!flag?el:null
                })
            }else{
                this.setData({
                    [key]: false
                })
            }
        })
        this.setData({
            'pages.curPage': 1,
            'pages.totalPage': 1,
            'pageLoad': false,
            'listData':null,
            'isNoMore':false
        })
        this.hideFilterBox()
        this.getIndexList()
    },
    changeTradeArea(e){
        let dataset = e.currentTarget.dataset;
        this.setData({
            'curTradeArea':dataset.item
        })
    },
    changeTradeAreaPart(e) {
        let dataset = e.currentTarget.dataset;
        let key = 'searchParamsData.sArea',key2 = 'searchParamsData.sDis'
        if(dataset.type == 1){
            this.setData({
                [key]: '',
                [key2]: dataset.item
            })
        }else{
            this.setData({
                [key2]: '',
                [key]: dataset.item
            })
        }
        this.setData({
            'pages.curPage': 1,
            'pages.totalPage': 1,
            'pageLoad': false,
            'listData': null,
            'isNoMore': false
        })
        this.hideFilterBox()
        this.getIndexList()
        
    }


})
